/*******************************************************************
 * Licensed under the MIT License:
 * Copyright (c) 2010, Nick Boumans (www.sharepointdevelopment.nl)
 * 
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:

 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 *******************************************************************
 * Feature: Mirjam van Olst
 * http://sharepointchick.com/archive/2010/03/26/deploying-a-custom-master-page-in-sharepoint-2010.aspx
 * Starter Publishing Masterpage: Randy Drisgill
 * http://startermasterpages.codeplex.com/releases/view/41533/ 
 * Mega Dropdown: Guillaume Marty
 * http://net.tutsplus.com/tutorials/html-css-techniques/how-to-build-a-kick-butt-css3-mega-drop-down-menu/
 * Mega Drop-Down Navigation Menus Work Well: Jakob Nielsen
 * http://www.useit.com/alertbox/mega-dropdown-menus.html
 *******************************************************************/


using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;

namespace SP2010_Starter.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("537836dc-9333-467d-88a8-c39f99e472c2")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        // Const Listname (name of the SPList)
        const string LISTNAME = "Mega Drop Down Menu";
        // Object holding the created List for Mega Drop Down Items
        SPList storageList;

        /// <summary>
        /// Code executed when the feature is activated
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {            
            SPSite curSite = (SPSite)properties.Feature.Parent;
            SPWeb curWeb = curSite.RootWeb;

            // Check or the List exists, if nog create it
            if (!ListExists(LISTNAME, curWeb))
            {
                CreateList(LISTNAME);
                if (storageList != null)
                {
                    // Create some sample menu items
                    // You can delete the sample items in production
                    CreateItems(storageList);
                }
                
            }

            // Create full master url
            Uri masterUri = new Uri(curWeb.Url + "/_catalogs/masterpage/Module1/_starter_publishing.master");

            // Master page used by all forms and pages on the site that are NOT publishing pages
            curWeb.MasterUrl = masterUri.AbsolutePath;
            // Master page used by all publishing pages on the site
            curWeb.CustomMasterUrl = masterUri.AbsolutePath;
            curWeb.Update();
        }

        /// <summary>
        /// Check or the list exists
        /// </summary>
        /// <param name="listName">the name of the list</param>
        /// <param name="site">SPWeb object</param>
        /// <returns></returns>
        private bool ListExists(string listName, SPWeb site)
        {
            try
            {
                SPList list = site.Lists[listName];
                if (list != null)
                {                   
                    return true;
                }
            }
            catch
            {

            }
            return false;
        }

        /// <summary>
        /// Create some items for demo purposes
        /// </summary>
        /// <param name="aList">Custom List object to create the items</param>
        private void CreateItems(SPList aList)
        {
            // Add a record to the new list
            SPListItem homeItem = aList.Items.Add();
            homeItem["Title of Menu Item"] = "Home";
            homeItem["ItemOrder"] = 0;
            homeItem["HTML"] = "<li><a href=\"#\" class=\"drop\">Home</a><!-- Begin Home Item -->" +
        "<div class=\"dropdown_2columns\"><!-- Begin 2 columns container -->" +
           "<div class=\"col_2\"><h2>Welcome !</h2></div> <div class=\"col_2\">" +
               " <p>Hi and welcome here ! This is a showcase of the possibilities of this awesome Mega Drop Down Menu.</p> " +            
               " <p>This item comes with a large range of prepared typographic stylings such as headings, lists, etc.</p>  " +           
            "</div><div class=\"col_2\"><h2>Cross Browser Support</h2></div><div class=\"col_1\">" +
            " <img src=\"/_layouts/images/sp2010_starter/browsers.png\" width=\"125\" height=\"48\" alt=\"\" />" +
            "</div><div class=\"col_1\"><p>This mega menu has been tested in all major browsers.</p></div>"+
            "</div><!-- End 2 columns container --></li><!-- End Home Item -->";

            homeItem.Update();

            // Add a record to the new list
            SPListItem fiveColumns = aList.Items.Add();
            fiveColumns["Title of Menu Item"] = "5 Columns";
            fiveColumns["ItemOrder"] = 1;
            fiveColumns["HTML"] = "<li><a href=\"#\" class=\"drop\">5 Columns</a><!-- Begin 5 columns Item -->" +
            "<div class=\"dropdown_5columns\"><!-- Begin 5 columns container -->" +
            "<div class=\"col_5\"><h2>This is an example of a large container with 5 columns</h2>" +
            "</div><div class=\"col_1\"><p class=\"black_box\">This is a dark grey box text. Fusce in metus at enim porta lacinia vitae a arcu. Sed sed lacus nulla mollis porta quis.</p>" +
            "</div><div class=\"col_1\"><p>Phasellus vitae sapien ac leo mollis porta quis sit amet nisi. Mauris hendrerit, metus cursus accumsan tincidunt.</p>" +
            "</div><div class=\"col_1\"><p class=\"italic\">This is a sample of an italic text. Consequat scelerisque. Fusce sed lectus at arcu mollis accumsan at nec nisi porta quis sit amet.</p>" +
            "</div><div class=\"col_1\"><p>Curabitur euismod gravida ante nec commodo. Nunc dolor nulla, semper in ultricies vitae, vulputate porttitor neque.</p>" +
            "</div><div class=\"col_1\"><p class=\"strong\">This is a sample of a bold text. Aliquam sodales nisi nec felis hendrerit ac eleifend lectus feugiat scelerisque.</p>" +
            "</div><div class=\"col_5\"><h2>Here is some content with side images</h2></div>" +
            "<div class=\"col_3\">" +
            "<img src=\"/_layouts/images/sp2010_starter/01.jpg\" width=\"70\" height=\"70\" class=\"img_left imgshadow\" alt=\"\" />" +
            "<p>Maecenas eget eros lorem, nec pellentesque lacus. Aenean dui orci, rhoncus sit amet tristique eu, tristique sed odio. Praesent ut interdum elit. Sed in sem mauris. Aenean a commodo mi. Praesent augue lacus.<a href=\"#\">Read more...</a></p>" +
            "<img src=\"/_layouts/images/sp2010_starter/02.jpg\" width=\"70\" height=\"70\" class=\"img_left imgshadow\" alt=\"\" />" +
            "<p>Aliquam elementum felis quis felis consequat scelerisque. Fusce sed lectus at arcu mollis accumsan at nec nisi. Aliquam pretium mollis fringilla. Nunc in leo urna, eget varius metus. Aliquam sodales nisi.<a href=\"#\">Read more...</a></p>" +
            "</div><div class=\"col_2\">" +
            "<p class=\"black_box\">This is a black box, you can use it to highligh some content. Sed sed lacus nulla, et lacinia risus. Phasellus vitae sapien ac leo mollis porta quis sit amet nisi. Mauris hendrerit, metus cursus accumsan tincidunt.Quisque vestibulum nisi non nunc blandit placerat. Mauris facilisis, risus ut lobortis posuere, diam lacus congue lorem, ut condimentum ligula est vel orci. Donec interdum lacus at velit varius gravida. Nulla ipsum risus.</p>" +
            "</div></div><!-- End 5 columns container --></li><!-- End 5 columns Item -->";

            fiveColumns.Update(); 

            // Add a record to the new list
            SPListItem fourColumns = aList.Items.Add();
            fourColumns["Title of Menu Item"] = "4 Columns";
            fourColumns["ItemOrder"] = 2;
            fourColumns["HTML"] = "<li><a href=\"#\" class=\"drop\">4 Columns</a><!-- Begin 4 columns Item -->" +
            "<div class=\"dropdown_4columns\"><!-- Begin 4 columns container -->" +
            "<div class=\"col_4\"><h2>This is a heading title</h2></div>" +
            "<div class=\"col_1\"><h3>Some Links</h3><ul>" +
                    "<li><a href=\"#\">ThemeForest</a></li>" +
                    "<li><a href=\"#\">GraphicRiver</a></li>" +
                    "<li><a href=\"#\">ActiveDen</a></li>" +
                    "<li><a href=\"#\">VideoHive</a></li>" +
                    "<li><a href=\"#\">3DOcean</a></li></ul></div>" +
            "<div class=\"col_1\"><h3>Useful Links</h3><ul>" +
                    "<li><a href=\"#\">NetTuts</a></li>" +
                    "<li><a href=\"#\">VectorTuts</a></li>" +
                    "<li><a href=\"#\">PsdTuts</a></li>" +
                    "<li><a href=\"#\">PhotoTuts</a></li>" +
                    "<li><a href=\"#\">ActiveTuts</a></li></ul></div>" +
            "<div class=\"col_1\"><h3>Other Stuff</h3><ul>" +
                    "<li><a href=\"#\">FreelanceSwitch</a></li>" +
                    "<li><a href=\"#\">Creattica</a></li>" +
                    "<li><a href=\"#\">WorkAwesome</a></li>" +
                    "<li><a href=\"#\">Mac Apps</a></li>" +
                    "<li><a href=\"#\">Web Apps</a></li></ul></div>" +
            "<div class=\"col_1\"><h3>Misc</h3><ul>" +
                    "<li><a href=\"#\">Design</a></li>" +
                    "<li><a href=\"#\">Logo</a></li>" +
                    "<li><a href=\"#\">Flash</a></li>" +
                    "<li><a href=\"#\">Illustration</a></li>" +
                    "<li><a href=\"#\">More...</a></li></ul></div>" +
            "</div><!-- End 4 columns container -->" +
            "</li><!-- End 4 columns Item -->";

            fourColumns.Update(); 

            // Add a record to the new list
            SPListItem oneColumn = aList.Items.Add();
            oneColumn["Title of Menu Item"] = "1 Column";
            oneColumn["ItemOrder"] = 3;
            oneColumn["HTML"] = "<li class=\"menu_right\"><a href=\"#\" class=\"drop\">1 Column</a>" +
            "<div class=\"dropdown_1column align_right\">" +
            "<div class=\"col_1\">" +
            "<ul class=\"simple\">" +
                        "<li><a href=\"#\">FreelanceSwitch</a></li>" +
                        "<li><a href=\"#\">Creattica</a></li>" +
                        "<li><a href=\"#\">WorkAwesome</a></li>" +
                        "<li><a href=\"#\">Mac Apps</a></li>" +
                        "<li><a href=\"#\">Web Apps</a></li>" +
                        "<li><a href=\"#\">NetTuts</a></li>" +
                        "<li><a href=\"#\">VectorTuts</a></li>" +
                        "<li><a href=\"#\">PsdTuts</a></li>" +
                        "<li><a href=\"#\">PhotoTuts</a></li>" +
                        "<li><a href=\"#\">ActiveTuts</a></li>" +
                        "<li><a href=\"#\">Design</a></li>" +
                        "<li><a href=\"#\">Logo</a></li>" +
                        "<li><a href=\"#\">Flash</a></li>" +
                        "<li><a href=\"#\">Illustration</a></li>" +
                        "<li><a href=\"#\">More...</a></li></ul></div></div></li>";

            oneColumn.Update();
 
            // Add a record to the new list
            SPListItem threeColumns = aList.Items.Add();
            threeColumns["Title of Menu Item"] = "3 Columns";
            threeColumns["ItemOrder"] = 4;
            threeColumns["HTML"] = "<li class=\"menu_right\"><a href=\"#\" class=\"drop\">3 columns</a><!-- Begin 3 columns Item -->" +
            "<div class=\"dropdown_3columns align_right\"><!-- Begin 3 columns container -->" +
            "<div class=\"col_3\"><h2>Lists in Boxes</h2></div><div class=\"col_1\">" +
            "<ul class=\"greybox\">" +
                    "<li><a href=\"#\">FreelanceSwitch</a></li>" +
                    "<li><a href=\"#\">Creattica</a></li>" +
                    "<li><a href=\"#\">WorkAwesome</a></li>" +
                    "<li><a href=\"#\">Mac Apps</a></li>" +
                    "<li><a href=\"#\">Web Apps</a></li></ul></div>" +
            "<div class=\"col_1\"><ul class=\"greybox\">" +
                    "<li><a href=\"#\">ThemeForest</a></li>" +
                    "<li><a href=\"#\">GraphicRiver</a></li>" +
                    "<li><a href=\"#\">ActiveDen</a></li>" +
                    "<li><a href=\"#\">VideoHive</a></li>" +
                    "<li><a href=\"#\">3DOcean</a></li></ul></div>" +
            "<div class=\"col_1\"><ul class=\"greybox\">" +
                    "<li><a href=\"#\">Design</a></li>" +
                    "<li><a href=\"#\">Logo</a></li>" +
                    "<li><a href=\"#\">Flash</a></li>" +
                    "<li><a href=\"#\">Illustration</a></li>" +
                    "<li><a href=\"#\">More...</a></li></ul></div>" +
            "<div class=\"col_3\"><h2>Here are some image examples</h2></div>" +
            "<div class=\"col_3\"><img src=\"/_layouts/images/sp2010_starter/02.jpg\" width=\"70\" height=\"70\" class=\"img_left imgshadow\" alt=\"\" />" +
            "<p>Maecenas eget eros lorem, nec pellentesque lacus. Aenean dui orci, rhoncus sit amet tristique eu, tristique sed odio. Praesent ut interdum elit. Maecenas imperdiet, nibh vitae rutrum vulputate, lorem sem condimentum.<a href=\"#\">Read more...</a></p>" +
            "<img src=\"/_layouts/images/sp2010_starter/01.jpg\" width=\"70\" height=\"70\" class=\"img_left imgshadow\" alt=\"\" />" +
            "<p>Aliquam elementum felis quis felis consequat scelerisque. Fusce sed lectus at arcu mollis accumsan at nec nisi. Aliquam pretium mollis fringilla. Vestibulum tempor facilisis malesuada. <a href=\"#\">Read more...</a></p></div></div><!-- End 3 columns container --></li><!-- End 3 columns Item -->";

            threeColumns.Update();
        }

        /// <summary>
        /// Delete a list by listname
        /// </summary>
        /// <param name="listName">The name of the list</param>
        private void DeleteList(String listName)
        {
            // Since not al users have list creation rights, run in elevated mode
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite oSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        // Add a record to the new list
                        SPListCollection lists = oWeb.Lists;
                        SPList list = lists[listName];
                        System.Guid listGuid = list.ID;

                        lists.Delete(listGuid);
                    }
                }
            });
        }

        /// <summary>
        /// Create a list based on a name
        /// </summary>
        /// <param name="listName"></param>
        private void CreateList(String listName)
        {
            // Since not al users have list creation rights, run in elevated mode
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite oSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        oWeb.AllowUnsafeUpdates = true;
                        // Add a record to the new list
                        SPListCollection lists = oWeb.Lists;

                        // Add a custom List to the SharePoint site
                        lists.Add(listName, "List containing Mega Drop Down Items", SPListTemplateType.GenericList);
                        // Put the new list in a variable
                        this.storageList = lists[listName];

                        // Get the out of the box fields (Title, Attachment etc)
                        SPFieldCollection fields = this.storageList.Fields;
                        // Change the default title column            
                        SPField field = fields["Title"];
                        field.Title = "Title of Menu Item";
                        // Don't forget the update to commit changes
                        field.Update();

                        // Add a new field
                        SPField fieldOrder = fields[fields.Add("ItemOrder", SPFieldType.Number, true)];
                        fieldOrder.Indexed = true;
                        fieldOrder.EnforceUniqueValues = true;
                        fieldOrder.Update();

                        SPField fieldHTML = fields[fields.Add("HTML", SPFieldType.Note, false)];
                        //TODO: Set plain text and number of lines)
                        fieldHTML.Update();

                        SPView view = this.storageList.DefaultView;
                        SPViewFieldCollection viewFields = view.ViewFields;

                        // Add the field to the defaultview (all items)
                        viewFields.Add(fieldOrder);
                        viewFields.Add(fieldHTML);

                        view.Update();
                       
                    }
                }
            });
        }        

        /// <summary>
        /// Deactivate the feature
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite curSite = (SPSite)properties.Feature.Parent;
            SPWeb curWeb = curSite.RootWeb;           

            if (ListExists(LISTNAME, curWeb))
            {
              DeleteList(LISTNAME);
            }

            // Create full master url
            Uri masterUri = new Uri(curWeb.Url + "/_catalogs/masterpage/v4.master");

            // Master page used by all forms and pages on this site that are NOT publishing pages
            curWeb.MasterUrl = masterUri.AbsolutePath;
            // Master page used by all publishing pages on the site
            curWeb.CustomMasterUrl = masterUri.AbsolutePath;
            curWeb.Update();

        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
